import mqtt from "mqtt";
import { Notification } from "element-ui";

class MqttReq {
  constructor() {
    this.client = {};
    this.msg = "";
  }

  connect(clientId, topics) {
    let options = {
      username: "admin",
      password: "public",
      cleanSession: false,
      keepAlive: 60,
      // clientId: 'topic' + Math.random().toString(16).substr(2, 8)
      clientId: clientId, // 'emqx_NjU1Mz' + Math.random().toString(16).substr(2, 8),
      // clientId: 'topic' + '1'
      connectTimeout: 4000
    };
    // this.client = mqtt.connect("ws://121.41.86.202:8083/mqtt", options);
    // this.client = mqtt.connect("ws://112.6.206.206:49131/mqtt", options);
    this.client = mqtt.connect("ws://10.50.34.13:8083/mqtt", options);

    this.client.on("connect", e => {
      console.log("成功连接服务器");
      // 订阅三个名叫'top/#', 'three/#'和'#'的主题
      this.client.subscribe(topics, { qos: 1 }, err => {
        if (!err) {
          console.log("订阅成功");
        } else {
          console.log("消息订阅失败！");
        }
      });
    });
    // 重新连接
    this.reconnect();
    // 是否已经断开连接
    this.mqttError();
    // 监听获取信息
    this.getMessage();
  }

  publish(topic, message) {
    if (!this.client.connected) {
      console.log("客户端未连接");
      return;
    }
    this.client.publish(topic, message, { qos: 1 }, err => {
      if (!err) {
        console.log("主题为" + topic + "发布成功");
      }
    });
  }

  getMessage() {
    this.client.on("message", (topic, message) => {
      console.log(topic, message);
      if (message) {
        console.log("收到来着", topic, "的信息", message.toString());
        const dispatch = JSON.parse(message.toString());
        // console.log(res, 'res')
        // this.$message(dispatch.name)
        // Message.warning(dispatch.name)
        Notification({
          title: "待分配调度",
          message: `有一条新的预警需要手动分配司机收运，请马上转到待分配调度页面处理。${dispatch.name}`,
          type: "warning",
          duration: 0
        });
      }
    });
  }

  mqttError() {
    this.client.on("error", error => {
      console.log("连接失败：", error);
      this.client.end();
    });
  }

  unsubscribe() {
    this.client.unsubscribe(this.mtopic, error => {
      console.log("主题为" + this.mtopic + "取消订阅成功", error);
    });
  }

  // 断开连接
  unconnect() {
    this.client.end();
    this.client = null;
    console.log("服务器已断开连接！");
  }

  // 监听服务器重新连接
  reconnect() {
    this.client.on("reconnect", error => {
      console.log("正在重连:", error);
    });
  }
}
export default MqttReq;
